package com.request.service.impl.shop.happy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.HappyErrorCodeEnum;
import com.request.common.enums.OperatorTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.entity.PhoneOrderAvailable;
import com.request.entity.PhoneOrderWaitPush;
import com.request.entity.out.PushOrderForHappy;
import com.request.service.PushOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Create DateTime: 2020/7/24 17:19
 *
 * 

 */
@Slf4j
@Service
public class HappyPushOrderProcessor implements PushOrderProcessor {

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendRequest(PhoneOrderWaitPush phoneOrderWaitPush) {
        handlerOrderExecutor.execute(() -> executeSend(phoneOrderWaitPush));
    }

    private void executeSend(PhoneOrderWaitPush phoneOrderWaitPush) {
        if (phoneOrderWaitPush == null) {
            return;
        }
        PhoneOrderAvailable phoneOrderAvailable = phoneOrderWaitPush.getPhoneOrderAvailable();
        PushOrderForHappy pushOrderForHappy = new PushOrderForHappy();

        String result = null;
        try {
            pushOrderForHappy.setMchid(phoneOrderWaitPush.getAppId());
            pushOrderForHappy.setTel(phoneOrderAvailable.getPhoneNum());
            pushOrderForHappy.setOrderid(phoneOrderAvailable.getPlatformOrderNo());
            pushOrderForHappy.setPrice(phoneOrderAvailable.getOrderPrice().setScale(0).toString());
            pushOrderForHappy.setTeltype(getHappyOperator(phoneOrderAvailable.getPhoneOperator()));
            pushOrderForHappy.setTimeout(phoneOrderAvailable.getOrderExpireTime().toString());
            pushOrderForHappy.setNotify(phoneOrderWaitPush.getShopCallbackSite());
            String time = System.currentTimeMillis() + "";
            pushOrderForHappy.setTime(time);
            String rand = RandomUtil.randomInt(100000, 999999) + "";
            pushOrderForHappy.setRand(rand);

            String sb = pushOrderForHappy.getMchid() +
                    pushOrderForHappy.getTel() +
                    pushOrderForHappy.getPrice() +
                    pushOrderForHappy.getOrderid() +
                    pushOrderForHappy.getTeltype() +
                    pushOrderForHappy.getTimeout() +
                    pushOrderForHappy.getNotify() +
                    pushOrderForHappy.getTime() +
                    pushOrderForHappy.getRand() +
                    phoneOrderWaitPush.getAppKey();
            String sign = SecureUtil.md5(sb);
            pushOrderForHappy.setSign(sign);

            log.info("【Happy】【推单】请求参数为：{}", pushOrderForHappy);

            try {
                result = sendRequestForPushOrder(phoneOrderWaitPush.getPushSite(), pushOrderForHappy);
            } catch (Exception e) {
                savePushOrderForException(phoneOrderWaitPush);
                savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
                log.info("【Happy】【推单】发送请求出现异常：", e);
                return;
            }
            log.info("【Happy】【推单】订单号为：{}, 结果:{}", phoneOrderAvailable.getPlatformOrderNo(), result);

            JSONObject json = JSONObject.parseObject(result);
            Integer code = json.getInteger("code");

            if (HappyErrorCodeEnum.SUCCESS.getCode() != code) {
                String msg = json.getString("msg");
                log.info("【Happy】【推单】响应状态标识位下单失败,响应状态码为：{}， 详细信息为：{}", code, msg);
                savePushOrderForFailed(phoneOrderWaitPush);
                return;
            }

            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
        } catch (Exception e) {
            savePushOrderForSuccess(phoneOrderAvailable.getPlatformOrderNo());
            log.error("【Happy】【推送订单】推送订单失败，待推送订单信息为：{}, 请求参数为：{}, 商户响应结果为：{}, 详细错误信息为：",
                    phoneOrderWaitPush, pushOrderForHappy, result, e);
        }
    }

    public String getHappyOperator(String operator) {
        if (OperatorTypeEnum.MOBILE.getCode().equals(operator)) {
            return "0";
        }
        if (OperatorTypeEnum.UNICOM.getCode().equals(operator)) {
            return "1";
        }
        if (OperatorTypeEnum.TELECOM.getCode().equals(operator)) {
            return "2";
        }
        return "";
    }


    /**
     * 发送Http请求
     *
     * @param url            请求路径
     * @param pushOrderForHappy 参数
     * @return 响应结果
     */
    private String sendRequestForPushOrder(String url, PushOrderForHappy pushOrderForHappy) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(pushOrderForHappy);
        return HttpUtils.doPost(url, paramMap);
    }

    /**
     * 放入失败队列
     */
    private void savePushOrderForFailed(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_RECORD, JSON.toJSONString(phoneOrderWaitPush));
    }

    /**
     * 放入成功队列
     */
    private void savePushOrderForSuccess(String platformOrderNo) {
        redisTemplate.opsForValue().set(RedisConstant.PUSH_ORDER_WAIT_PUSH_SUCCESS + platformOrderNo, platformOrderNo, 30, TimeUnit.MINUTES);
    }

    /**
     * 放入发送出现异常的队列
     */
    private void savePushOrderForException(PhoneOrderWaitPush phoneOrderWaitPush) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_PUSH_EXCEPTION, JSON.toJSONString(phoneOrderWaitPush));
    }

}
